package com.city58
{
	import com.base.data.account.AccountBean;
	import com.base.data.message.HousePropertyRight;
	import com.base.data.message.HouseType1;
	import com.base.data.message.MessageBean;
	import com.base.log.Log;
	import com.base.login.Login;
	import com.base.properties.Properties;
	import com.base.properties.PropertiesManmger;
	import com.base.send.SendMessage;
	import com.base.ui.other.StatusWindow;
	import com.base.util.MultiPartFormData;
	import com.base.util.Utils;
	
	import flash.desktop.NativeProcess;
	import flash.errors.IOError;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.html.HTMLLoader;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	
	public class City58Send extends SendMessage
	{
		public var accounts:Array;
		
		public var messageBean:MessageBean;
		
		public var success:Function;
		
		public var error:Function;
		
		public var that:*;
		
		public var login:Login;
		
		public var context:String;
		
		public function City58Send()
		{
			super();
			this.that = this;
		}
		
		override public function send(accounts:Array, message:MessageBean, success:Function, error:Function):void {
			this.accounts = accounts;
			this.messageBean = message;
			this.success = success;
			this.error = error;
			if( accounts.length == 0 ) {
				loginError( null );
				return;
			}
			var account:AccountBean = accounts.shift();
			login = new City58Login().login( account , loginComplete , loginError , false );
			StatusWindow.addText( "用户名："+account.userName+" 开始登陆58");
		}
		
		
		private function loginComplete( params:* ):void {
			StatusWindow.addText("用户名："+City58Login(params).account.userName+"登录成功，开始发送"+messageBean.titleStr+"的帖子");
			sendMessage();
		}
		
		private function loginError( params:* ):void {
			if( params ) StatusWindow.addText("账号登录失败，原因为:"+ Utils.text_zh( params.content ) );
				
			if( accounts.length > 0 ) {
				
				StatusWindow.addText("尝试切换账号登录");
				var account:AccountBean = accounts.shift();
				login.login( account , loginComplete , loginError , false );
				
			} else {
				
				context = "无法完成发帖,没有足够的可以发帖的账号";
				error( this );
			}
			
		}
		/**
		 * 发送帖子 
		 */		
		private function sendMessage():void {
			var properties:Properties =  PropertiesManmger.instance.getCity58Cfg() 
			var byte:MultiPartFormData = new MultiPartFormData();
			/*** 没有的字段 **/
			byte.addData("type","0");
			byte.addData("diduan","[|#|@]");
			byte.addData("diduan2","[|#|@]");
			
			byte.addData("daxue","");						//大学
			byte.addData("xianluzhoubian","");			//线路周边
			byte.addData("ditiexian","");					//地铁线
			byte.addData("stationdistance","");			//站距离?
			byte.addData("ditiezhan","");					//地铁线
			byte.addData("gongjiaoxian","");				//公交线
			byte.addData("busdistance","");
			byte.addData("gongjiaozhan","")				//公交站
			byte.addData("distancetime","");
			byte.addData("localDiduan","");
			byte.addData("taoneimianji","");
			
			byte.addData("__hidden_iqasincode","1");
//			tbx_backfill_smscode	340124
			/**
			 * 手动拼凑
			 **/
			byte.addData("iqas_mcresult","186207245"); //服务器时间 精确到日期
			byte.addData("xiaobao_option","0");			//不知道干什么用的
			byte.addData("huxingshi",messageBean.houseType.room+"");
			byte.addData("BuildingEra",(new Date().fullYear - messageBean.housePropertyRight.buildTime)+"");
			byte.addData("dingceng", (messageBean.houseStorey.totalStorey == messageBean.houseStorey.currStorey ? 1: 0)+"" );
			var golbalsokey:String = messageBean.areaName
									+"|"+messageBean.houseType.room+"居室,"+messageBean.houseType.room+"居,"+messageBean.houseType.room+"室"
									+"|"+messageBean.houseType.squareMeters+"平米"
									+"|"+messageBean.houseTotalPrice.price
									+"|"+Utils.findDataByArray(HouseType1.AppearanceList ,messageBean.houseType1.appearance)["label"]
									+"|"+Utils.findDataByArray(HouseType1.FitmentList , messageBean.houseType1.fitment)["label"]
									+"|"+Utils.findDataByArray(HousePropertyRight.PropertyRightType , messageBean.housePropertyRight.propertyRightType)["label"]
									+"|"+messageBean.houseStorey.currStorey+"层,"+messageBean.houseStorey.currStorey+"楼";
									
			byte.addData("gobalsokey",golbalsokey);		//gobalsokey	小区名字|9居室,9居,9室|160平米|80|普通住宅|简单装修|商品房|3层,3楼
			
			var fangyuanteseArr:Array = new Array( messageBean.houseFeature.feature1,messageBean.houseFeature.feature2
												 ,messageBean.houseFeature.feature3,messageBean.houseFeature.feature4 );
			
			var peitaosheshiArr:Array = new Array(messageBean.houseFacility.facility1 ,messageBean.houseFacility.facility2 
												 ,messageBean.houseFacility.facility3 ,messageBean.houseFacility.facility4 );
			
			byte.addData("hiddenTextBoxJoinValue",messageBean.areaName+":"+messageBean.advertisement +":"+messageBean.linkman );	//小区名称+一句话广告+8个自定义标签+联系人
			var s:String = "";
			var to:String;
			
			for each( to in fangyuanteseArr ) {
				if( to != null && to != "" ) {
					s += int(99*Math.random()+1) + "@"+to+"#";
				}
			}
			
			s = s.substr( 0 , s.length -1 );
			byte.addData("fangyuantese",s );
			
			s = "";
			for each( to in peitaosheshiArr ) {
				if( to != null && to != "" ) {
					s += int(99*Math.random()+1) + "@"+to+"#";
				}
			}
			s = s.substr( 0 , s.length -1 );
			byte.addData("peitaosheshi", s );
			
			
			/** 同样的帖子防止58认定重复贴 **/
		
			byte.addData("Content",getContextStr());
			byte.addData("Title",getTitleStr() );
			
			
			/** 图片暂时不弄 **/
			byte.addData("bigpic","0");
			byte.addData("pic","");
			byte.addData("pictag","");
			byte.addData("picdesc1","");
			byte.addData("picdesc2","");
			byte.addData("picdesc3","");
			byte.addData("picdesc4","");
			byte.addData("picdesc5","");
			byte.addData("picdesc6","");
			byte.addData("picdesc7","");
			byte.addData("picdesc8","");
			
			byte.addMessage( messageBean , properties );
			byte.pack();
			
			
			var request:URLRequest = new URLRequest( properties.getProperty("sendUrl") );
			request.method = URLRequestMethod.POST;
			request.data = byte.data;
			
			var header:URLRequestHeader = new URLRequestHeader ("Content-Type", "multipart/form-data; boundary="+MultiPartFormData.Boundary);
			request.requestHeaders.push(header);
			
			var load:URLLoader = new URLLoader();
			load.load( request );
			load.addEventListener( Event.COMPLETE , onComplete );
			load.addEventListener( IOErrorEvent.IO_ERROR ,onError );
		}
		
		private static var specialChars:Array = ["	","　","","","","","","","",""];
		
		private function getTitleStr():String {
			
			var insertPoint:Boolean = int( Math.random() * 9 ) >= 5;
			
			var specialLen:int =  Math.random()*( 28-messageBean.titleStr.length );
			
			var specialStr:String = "";
			
			for( var i:int = 0 ; i < specialLen; i++ ) {
				specialStr += specialChars[ int( Math.random() * specialChars.length ) ];
			}
			
			var titleStr:String = insertPoint ? specialStr+messageBean.titleStr : messageBean.titleStr+specialStr;
			return titleStr;
		}
		
		private static var specialChars1:Array = ["&nbsp;","&emsp;","&#09;","&#32;","&#10;","&#13;","&shy;"
																		,"<br/>","<br></br>","<u/>","<u></u>","<font>","<font></font>"];
		private function getContextStr():String {
			
			var insertPoint:Boolean = int( Math.random() * 9) >= 5;
			
			var specialLen:int =  Math.random() * ( insertPoint ? 10 : 100);
			
			var specialStr:String = "";
			
			for( var i:int = 0 ; i < specialLen; i++ ) {
				specialStr += specialChars1[ int( Math.random() * specialChars1.length ) ];
			}
			
			var contextStr:String = insertPoint ? specialStr+messageBean.detailIntroduce : messageBean.detailIntroduce+specialStr;
			return contextStr;
			
			
		}
		
		private var retry:int = 0;
		private function onComplete( e:Event ):void {
			e.target.removeEventListener( IOErrorEvent.IO_ERROR , onError );
			e.target.removeEventListener( e.type , onComplete );
			
			context = String(e.target.data);
			
			Log.log("58发帖响应" , context );
			
			var i:int = context.indexOf("这条信息的详细描述与其他信息太过相似");
			var j:int = context.indexOf("这条信息的标题与其他信息太过相似");
			var k:int = context.indexOf("这条信息已经被您自己或别人发布过");
			var l:int = context.indexOf("您发布信息太过频繁");
			var u:int = context.indexOf("地址里不允许填写电话");
			
			if( i != -1 || j != -1  || k != -1 || l != -1 || u != -1 ) {
				retry++;
				if( retry <= 3 ) {
					StatusWindow.addText("发帖不成功。尝试重新发帖。");
					sendMessage();
					
				} else {
					
					login.logout();
					error( this );
				}
				
				return;
			}
			
			var t:int = context.indexOf("您所在的等级今天在二手房只能发布");
			if( t != -1 ) {	//用户达到发帖上线,切换账号发帖。
				login.logout();
				StatusWindow.addText( Utils.text_zh( context ) );
				loginError( null );
				return;
			}
			
			var h:int = context.indexOf("$.bll.iqas.sms_init");
			if( h != -1 ) {
				
				context = "电话号码已绑定账号,请更换电话号码";
				login.logout();
				error( this );
				
				return;
			}
			
			login.logout();
			
			success( this );
		}
		
		private function onError( e:IOErrorEvent ):void {
			
			e.target.removeEventListener( Event.COMPLETE , onComplete );
			e.target.removeEventListener( e.type , onError );
			
			context = "58发帖出现网络错误 ";
			Log.log("58发帖出现错误", e.toString() );
			
			login.logout();
			error( this );
		}
		
	}
}